package handlers

import (
	"k8s-service/service"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// 使用 service 层的请求结构
type ChatCompletionRequest = service.ChatCompletionRequest
type EmbeddingRequest = service.EmbeddingRequest
type RerankerRequest = service.RerankerRequest

// ErrorResponse 错误响应结构
type ErrorResponse struct {
	Error ErrorDetail `json:"error"`
}

// ErrorDetail 错误详情结构
type ErrorDetail struct {
	Message string `json:"message"`
	Type    string `json:"type"`
	Code    string `json:"code"`
}

// 代理服务实例
var proxyService *service.ProxyService

// SetProxyService 设置代理服务实例
func SetProxyService(ps *service.ProxyService) {
	proxyService = ps
}

// InvalidateProxyCache 使缓存失效（在模型配置更新时调用）
func InvalidateProxyCache() {
	if proxyService != nil {
		proxyService.InvalidateCache()
	}
}

// ChatCompletions 处理聊天完成请求
// @Summary 聊天完成接口
// @Description 兼容 OpenAI 的聊天完成接口，支持流式和非流式响应
// @Tags 代理接口
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer token"
// @Param request body ChatCompletionRequest true "聊天请求"
// @Success 200 {object} interface{}
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /v1/chat/completions [post]
func ChatCompletions(c *gin.Context) {
	var req ChatCompletionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{
			Error: ErrorDetail{
				Message: "Invalid request: " + err.Error(),
				Type:    "invalid_request_error",
				Code:    "invalid_request",
			},
		})
		return
	}

	// 处理聊天完成请求的业务逻辑
	modelConfig, err := proxyService.ProcessChatCompletion(&req)
	if err != nil {
		c.JSON(http.StatusNotFound, ErrorResponse{
			Error: ErrorDetail{
				Message: err.Error(),
				Type:    "invalid_request_error",
				Code:    "model_not_found",
			},
		})
		return
	}

	// 代理请求
	if err := proxyService.ProxyRequest(c, modelConfig, &req, 60*time.Second); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{
			Error: ErrorDetail{
				Message: "Proxy request failed: " + err.Error(),
				Type:    "api_error",
				Code:    "internal_error",
			},
		})
		return
	}
}

// Embeddings 处理嵌入请求
// @Summary 嵌入接口
// @Description 兼容 OpenAI 的嵌入接口，支持字符串和字符串数组格式的input
// @Tags 代理接口
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer token"
// @Param request body EmbeddingRequest true "嵌入请求"
// @Success 200 {object} interface{}
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /v1/embeddings [post]
func Embeddings(c *gin.Context) {
	var req EmbeddingRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{
			Error: ErrorDetail{
				Message: "Invalid request: " + err.Error(),
				Type:    "invalid_request_error",
				Code:    "invalid_request",
			},
		})
		return
	}

	// 处理嵌入请求的业务逻辑
	modelConfig, err := proxyService.ProcessEmbedding(&req)
	if err != nil {
		c.JSON(http.StatusNotFound, ErrorResponse{
			Error: ErrorDetail{
				Message: err.Error(),
				Type:    "invalid_request_error",
				Code:    "model_not_found",
			},
		})
		return
	}

	// 代理请求
	if err := proxyService.ProxyRequest(c, modelConfig, &req, 30*time.Second); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{
			Error: ErrorDetail{
				Message: "Proxy request failed: " + err.Error(),
				Type:    "api_error",
				Code:    "internal_error",
			},
		})
		return
	}
}

// Rerank 处理重排序请求
// @Summary 重排序接口
// @Description 兼容 Reranker 接口，对文档进行重排序
// @Tags 代理接口
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer token"
// @Param request body RerankerRequest true "重排序请求"
// @Success 200 {object} interface{}
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /v1/rerank [post]
func Rerank(c *gin.Context) {
	var req RerankerRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{
			Error: ErrorDetail{
				Message: "Invalid request: " + err.Error(),
				Type:    "invalid_request_error",
				Code:    "invalid_request",
			},
		})
		return
	}

	// 处理重排序请求的业务逻辑
	modelConfig, err := proxyService.ProcessRerank(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{
			Error: ErrorDetail{
				Message: err.Error(),
				Type:    "invalid_request_error",
				Code:    "invalid_input",
			},
		})
		return
	}

	// 代理请求
	if err := proxyService.ProxyRequest(c, modelConfig, &req, 30*time.Second); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{
			Error: ErrorDetail{
				Message: "Proxy request failed: " + err.Error(),
				Type:    "api_error",
				Code:    "internal_error",
			},
		})
		return
	}
}
